package com.chexiehui.jc.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.SeriesBannerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.mvp.car.CarGarageAssistantDetailsCovenant;
import com.chexiehui.jc.mvp.car.CarGarageAssistantDetailsPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.FixedSpeedScroller;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.CircleImageView;
import com.chexiehui.jc.widget.CustomXPopupImageLoader;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NoScrollListView;
import com.lxj.xpopup.XPopup;
import com.tmall.ultraviewpager.UltraViewPager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zzhoujay.richtext.RichText;

import java.lang.reflect.Field;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 二手车详情
 */
public class CarGarageAssistantDetailsActivity extends BaseMvpActivity<CarGarageAssistantDetailsPresenter> implements CarGarageAssistantDetailsCovenant.View {
    @BindView(R.id.iv_car_image)
    ImageView ivCarImage;
    @BindView(R.id.ultra_banner)
    UltraViewPager ultraViewPager;
    @BindView(R.id.tv_car_price)
    TextView tvCarPrice;
    @BindView(R.id.tv_agent_price)
    TextView tvAgentPrice;
    @BindView(R.id.tv_car_name)
    TextView tvCarName;
    @BindView(R.id.tv_car_look_address)
    TextView tvCarLookAddress;
    @BindView(R.id.iv_merchant_avatar)
    CircleImageView ivMerchantAvatar;
    @BindView(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @BindView(R.id.tv_merchant_brief)
    TextView tvMerchantBrief;
    @BindView(R.id.rtv_merchant_call)
    RadiusTextView rtvMerchantCall;
    @BindView(R.id.tv_base_info_title)
    TextView tvBaseInfoTitle;
    @BindView(R.id.tv_car_time)
    TextView tvCarTime;
    @BindView(R.id.tv_car_mileage)
    TextView tvCarMileage;
    @BindView(R.id.tv_car_color)
    TextView tvCarColor;
    @BindView(R.id.tv_car_info_title)
    TextView tvCarInfoTitle;
    @BindView(R.id.tv_car_content)
    TextView tvCarContent;

    @BindView(R.id.nslv_other_car_list)
    NoScrollListView nslvOtherCarList;
    @BindView(R.id.rtv_call)
    RadiusTextView rtvCall;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.ll_like_container)
    LinearLayout llLikeContainer;
    private CarInfo carInfo;
    private String carId;
    private SeriesBannerAdapter seriesBannerAdapter;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            carId = bundle.getString("carId");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String id = bundle.getString("carId");
            if (!StringUtils.isTrimEmpty(id) && getCarId().equals(id)) {
                return;
            }
            carId = id;
        } else {
            return;
        }
        if (StringUtils.isTrimEmpty(getCarId())) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车源信息");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getDetailsInfo();
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("车辆详情");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_car_garage_assistant_details;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        if (StringUtils.isTrimEmpty(carId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车辆信息");
            return;
        }
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getDetailsInfo();
        });
        mvpPresenter.getDetailsInfo();
    }

    private void setCarInfo() {
        if (carInfo != null) {
            /*GlideUtil.loadImageViewCrop(mContext, carInfo.getImg(), ivCarImage,
                    R.drawable.shape_square, R.drawable.shape_square);*/
            initBanner();
            tvCarName.setText(carInfo.getBrandName() + " " + carInfo.getSeriesName() + " " + carInfo.getName());
            tvCarPrice.setText(carInfo.getPriceUnit());
            tvAgentPrice.setText(carInfo.getAgentPriceStr());
            tvCarLookAddress.setText("看车地点：" + carInfo.getCity());
            GlideUtil.loadImageViewCrop(mContext, carInfo.getPhoto(), ivMerchantAvatar,
                    R.drawable.shape_circle, R.drawable.shape_circle);
            tvMerchantName.setText(carInfo.getUserName());
            tvMerchantBrief.setText(carInfo.getCarAuth());
            tvCarTime.setText(carInfo.getRegistrationYearMonthStr());
            tvCarMileage.setText(carInfo.getDrivingDistanceStr());
            tvCarColor.setText(carInfo.getColor());
            if(StringUtils.isTrimEmpty(carInfo.getContent())){
                tvCarContent.setText("");
            }else{
                RichText.from(carInfo.getContent())
                        .imageClick((imageUrls, position) -> {
                            try {
                                new XPopup.Builder(mContext)
                                        .asImageViewer(null, position, (List) imageUrls, null, new CustomXPopupImageLoader())
                                        .show();
                            }catch (Exception e){}
                        })
                        .into(tvCarContent);
            }
            if (carInfo.getReList() == null || carInfo.getReList().size() < 1) {
                llLikeContainer.setVisibility(View.GONE);
            } else {
                llLikeContainer.setVisibility(View.VISIBLE);
                nslvOtherCarList.setAdapter(new CommonAdapter<CarInfo>(mContext,
                        R.layout.item_car_garage_assistant, carInfo.getReList()) {
                    @Override
                    protected void convert(ViewHolder holder, CarInfo item, int position) {
                        GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.iv_item_image),
                                R.drawable.shape_square, R.drawable.shape_square);
                        holder.setText(R.id.tv_item_name, item.getBrandName() + " " + item.getSeriesName() + " " + item.getName());
                        holder.setText(R.id.tv_item_area, item.getCity());
                        holder.setText(R.id.tv_item_year, item.getRegistrationYear());
                        holder.setText(R.id.tv_item_mileage, item.getDrivingDistance() + "万公里");
                        holder.setText(R.id.tv_item_price, item.getPriceUnit());
                        holder.setText(R.id.tv_item_agent_price, item.getAgentPriceStr());
                    }
                });
                nslvOtherCarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (NoDoubleClickUtils.isDoubleClick()) return;
                        carId = carInfo.getReList().get(position).getId();
                        loadingLayout.setStatus(LoadingLayout.Loading);
                        mvpPresenter.getDetailsInfo();/*
                        startActivity(CarGarageAssistantDetailsActivity.class,
                                new BundleBuilder().putString("carId", carInfo.getReList().get(position).getId()).create());*/
                    }
                });
            }
        } else {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无车辆信息");
        }
    }

    private void initBanner() {
        if (carInfo.getImgs().size() > 0) {
            ultraViewPager.setVisibility(View.VISIBLE);
            ivCarImage.setVisibility(View.GONE);
            ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
            try {
                Field mField;
                mField = ViewPager.class.getDeclaredField("mScroller");
                mField.setAccessible(true);
                FixedSpeedScroller mScroller =
                        new FixedSpeedScroller(mContext, new AccelerateInterpolator());
                mScroller.setmDuration(1000);
                mField.set(ultraViewPager.getViewPager(), mScroller);
            } catch (Exception e) {
            }
            ultraViewPager.setAutoMeasureHeight(false);
            seriesBannerAdapter = new SeriesBannerAdapter(carInfo.getImgs(), (url, isVideo) -> {
                if (isVideo) {
                    VideoPlayActivity.start(CarGarageAssistantDetailsActivity.this, carInfo.getName(), url);
                } else {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, url, new CustomXPopupImageLoader())
                                .show();
                    } catch (Exception e) {
                    }
                }
            });
            ultraViewPager.setAdapter(seriesBannerAdapter);
            //内置indicator初始化
            ultraViewPager.initIndicator();
            //设置indicator样式
            ultraViewPager.getIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.colorWhite))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.c_999999))
                    .setRadius(SizeUtils.dp2px(4));
            //设置indicator对齐方式
            ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            ultraViewPager.getIndicator().setMargin(0, 0, 0, SizeUtils.dp2px(10));
            //构造indicator,绑定到UltraViewPager
            ultraViewPager.getIndicator().build();
            //设定页面循环播放
            ultraViewPager.setInfiniteLoop(true);
            //设定页面自动切换  间隔5秒
            ultraViewPager.setAutoScroll(5000);
        } else {
            ultraViewPager.setVisibility(View.GONE);
            ivCarImage.setVisibility(View.VISIBLE);
            GlideUtil.loadImageViewCrop(mContext, carInfo.getImg(), ivCarImage,
                    R.drawable.shape_square, R.drawable.shape_square);
            ivCarImage.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View view) {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(ivCarImage, carInfo.getImg(), new CustomXPopupImageLoader())
                                .show();
                    } catch (Exception e) {
                    }
                }
            });
        }
    }

    @Override
    protected CarGarageAssistantDetailsPresenter createPresenter() {
        return new CarGarageAssistantDetailsPresenter(this);
    }

    @Override
    public void onGetDetailsInfoSuccess(BaseModel<CarInfo> successResult) {
        loadingLayout.setStatus(LoadingLayout.Success);
        carInfo = successResult.getData();
        setCarInfo();
    }

    @Override
    public void onGetDetailsInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public String getCarId() {
        return carId == null ? "" : carId;
    }

    @OnClick({R.id.rtv_merchant_call, R.id.rtv_call})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) return;
        switch (view.getId()) {
            case R.id.rtv_merchant_call:
            case R.id.rtv_call:
                if (StringUtils.isTrimEmpty(carInfo.getTel())) {
                    showToast("暂无电话信息");
                    return;
                }
                UIAlertDialog dialog = new UIAlertDialog.DividerIOSBuilder(mContext)
                        .setTitle("拨打电话")
                        .setMessage(carInfo.getTel())
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                callPhone();
                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();
                break;
        }
    }

    private void callPhone() {
        AndPermission.with(this)
                .permission(Permission.PHONE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PhoneUtils.call(carInfo.getTel());
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权电话权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }
}
